#include "HttpServer.hpp"
#include <memory>
#include <string>
using namespace std;
using namespace server;

// 1、服务器和网页分离
// 2、url -> / -> web根目录
// 3、我们要正确的给客户端返回资源类型，那么我们要先知道资源是什么类型的！ —— 所有资源都有后缀
string suffixToDesc(string suffix) // 通过后缀，拼接对应的报文长度
{
    string ct = "Content-Type:";
    if (suffix == ".html")
        ct += "text/html";
    else if (suffix == ".jpg")
        ct += "application/x-jpg";

    ct += "\r\n";
    return ct;
}
bool Get(const HttpRequest &req, HttpResponse &resp)
{
    cout << "---------------------http start--------------------" << endl;
    cout << req.inbuffer << endl;
    cout << "method:" << req.method << endl;
    cout << "url:" << req.url << endl;
    cout << "httpversion:" << req.httpversion << endl;
    cout << "path:" << req.path << endl;
    cout << "suffix:" << req.suffix << endl;
    cout << "size:" << req.size << endl;
    cout << "---------------------http end----------------------" << endl;
    string respline = "HTTP/1.1 200 OK\r\n";       // 响应状态第一行
    string resphandler = suffixToDesc(req.suffix); // 资源类型
    if (req.size > 0)
    {
        resphandler += "Content-Length:";
        resphandler += to_string(req.size); // 正文长度
        resphandler += "\r\n";
    }
    string respblank = "\r\n"; // 空行
    // 正文
    // string body = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>fot test</title><h1>hello world</h1></head><body><p>并且你不介意这个警告，你可以使用编译器选项来忽略这个特定的警告</p></body></html>";
    // 不进行硬编码了
    string body;
    if (!Util::readFile(req.path, &body)) // 把文本文件的内容读取到字符串里面，从path读取到body里面去
    {
        Util::readFile(html_404, &body); // 如果文本文件内容读取失败，就将我们自己定义的404文件读取到
    }
    resp.outbuffer += respline; // 拼接
    resp.outbuffer += resphandler;

    resp.outbuffer += respblank;
    resp.outbuffer += body;
    return true;
}

void Usage(const string proc)
{
    cout << "Usage\n\t" << proc << "prot\r\n\r\n";
}
//./httpserver   8080
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(server::Usage_ERR);
    }
    uint16_t port = stoi(argv[1]);
    unique_ptr<server::httpserver> httpsvr(new server::httpserver(Get, port));
    httpsvr->initserver();
    httpsvr->start();
    return 0;
}